# Create your views here.
import os

from django.views import View

from model.Constants import PointImagePath
from model.models import Point, User
from server.utils import Response, LoginRequiredPerson, Verify, Code


class PointPhotoView(LoginRequiredPerson, View):
    """ User operation points photo """

    def get(self, request):
        """ Get image information for this point """
        name = request.GET.get('name')

        imagePath = os.path.join(PointImagePath, name)
        image = None
        if os.path.exists(imagePath):
            image = open(imagePath, 'rb')
        return Response.Image(image)

    def post(self, request):
        """ Upload the image information of this point """
        pid = request.POST.get('pid')
        photo = request.FILES.get('photo')

        for code in [Verify.pointPhoto(photo), Verify.pointPid(pid)]:
            if code != Code.OK:
                return Response.Json(code=code)

        point = Point.objects.get(pid=pid)

        if request.user.role != User.Role.super_admin:
            if point.uploader != request.user:
                return Response.Json(code=Code.Error, msg="You don't have permission to set someone else's points")

        name = point.setPhoto(photo)
        return Response.Json(name=name)
